package com.woniuxy.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;

@Component
public class PidNumRoutePredicateFactory extends AbstractRoutePredicateFactory<PidNumRoutePredicateFactory.Config> {
    ////确保抛出的是PidNumRoutePredicateFactory里面的Config的class对象
    public PidNumRoutePredicateFactory() {
        super(PidNumRoutePredicateFactory.Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new GatewayPredicate() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String[] paths = serverWebExchange.getRequest().getURI().getPath().split("/");
                //判断是否为数字
                Pattern pattern = Pattern.compile("^[\\-0-9][0-9]*(.[0-9]+)?");
                if (pattern.matcher(paths[paths.length - 2]).matches() && pattern.matcher(paths[paths.length - 1]).matches()){
                    int pid = Integer.valueOf(paths[paths.length - 2]);
                    int num = Integer.valueOf(paths[paths.length - 1]);
                    if (pid >= config.getMinPid() && pid <= config.getMaxPid() && num >= config.getMinNum() && num <= config.getMaxNum()) {
                        return true;
                    } else {
                        return false;
                    }
                }else {
                    return false;
                }
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minPid", "maxPid", "minNum", "maxNum");
    }

    //静态内部类：它和 写外面是一样的！
    public static class Config {
        private Integer minPid;
        private Integer maxPid;
        private Integer minNum;
        private Integer maxNum;

        public Integer getMinPid() {
            return minPid;
        }

        public void setMinPid(Integer minPid) {
            this.minPid = minPid;
        }

        public Integer getMaxPid() {
            return maxPid;
        }

        public void setMaxPid(Integer maxPid) {
            this.maxPid = maxPid;
        }

        public Integer getMinNum() {
            return minNum;
        }

        public void setMinNum(Integer minNum) {
            this.minNum = minNum;
        }

        public Integer getMaxNum() {
            return maxNum;
        }

        public void setMaxNum(Integer maxNum) {
            this.maxNum = maxNum;
        }
    }
}
